package com.java8.hexininterface;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * Java8 内置的四大核心函数式接口
 *
 *  Consumer<T> : 消费型接口
 *          void accept(T t);
 *
 *  Supplier<T> : 供给型接口
 *          T get();
 *
 *  Function<T, R> : 函数型接口
 *      R apply(T t);
 *
 *  Predicate<T> : 断言型接口
 *      boolean test(T t);
 *
 *
 */
public class TestInterFace {


    //Consumer<T> 消费型接口 : 没有返回值
    @Test
    public void test1() {
        happy(1000, m -> System.out.println("消费了:" + m));
    }


    public void happy(double money, Consumer<Double> consumer) {
        consumer.accept(money);
    }

    //Supplier<T> : 供给型接口
    @Test
    public void test2() {
        List<Integer> numList = getNumList(10, () -> (int) (Math.random() * 100));

        numList.forEach(System.out::println);
    }

    //需求:产生一些指定个数的整数,并放入集合中
    public List<Integer> getNumList(int num, Supplier<Integer> supplier) {
        List<Integer> list = new ArrayList<>();
        for(int i = 0; i < num; i++) {
            Integer integer = supplier.get();
            list.add(integer);
        }
        return list;
    }


    //Function<T, R> : 函数型接口
    @Test
    public void test3() {
        //去除首位空格和制表符
        String strHandler = strHandler("\t\t\t 我大尚硅谷威武", (str) -> str.trim());
        System.out.println(strHandler);


        //截取
        String strHandler1 = strHandler("我大尚硅谷威武", s -> s.substring(2, 5));
        System.out.println(strHandler1);
    }


    //需求: 用于处理字符串
    public String strHandler(String str, Function<String, String> fun) {
        return fun.apply(str);
    }


    //Predicate<T> 断言型接口:
    @Test
    public void test4() {
        List<String> list = Arrays.asList("Hello", "atguigu", "Lambda", "www", "ok");
        List<String> strings = filterStr(list, s -> s.length() > 3);

        strings.forEach(System.out::println);
    }


    //需求:将满足条件的字符串放入集合中去
    public List<String> filterStr(List<String> stringList, Predicate<String> predicate) {
        List<String> list = new ArrayList<>();

        for(String str : stringList) {
            if (predicate.test(str)) {
                list.add(str);
            }
        }

        return stringList;
    }
}
